package com.youlu.campus.starter.sms.config;

import lombok.extern.slf4j.Slf4j;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

/**
 * ok http 重试拦截器
 */
@Slf4j
public class ErrorRetryInterceptor implements Interceptor {

    /**
     * 最大重试次数
     */
    private final int maxRetries;

    /**
     * 重试等待时间 秒
     */
    private final int retrySleepTime;

    public ErrorRetryInterceptor(int maxRetries, int retrySleepTime) {
        this.maxRetries = maxRetries;
        this.retrySleepTime = retrySleepTime;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = null;
        IOException exception = null;

        //第一次请求
        try {
            response = chain.proceed(request);
            return response; // 网络请求 成功则返回
        } catch (IOException e) {
            exception = e; // 记录异常
            log.error("SmsOkhttpClient RetryInterceptor error e:{}", e);
        }
        // 尝试重试
        for (int i = 1; i <= maxRetries; i++) {
            try {
                response = chain.proceed(request);
                log.error("SmsOkhttpClient RetryInterceptor success retryNum:{}", i);
                return response; // 网络请求 成功则返回
            } catch (IOException e) {
                exception = e; // 记录异常
                log.error("SmsOkhttpClient RetryInterceptor error retryNum:{},e:{}", i, e);
            }
            //非最后一次重试时等待
            if (i < maxRetries && retrySleepTime > 0) {
                try {
                    Thread.sleep(retrySleepTime * 1000); // 间隔1秒
                } catch (InterruptedException ignored) {
                    Thread.currentThread().interrupt();
                }
            }
        }
        // 所有重试均失败
        if (exception != null) {
            throw exception;
        } else {
            throw new IOException("Unknown error");
        }
    }
}